package com.jushu.storbox;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Message;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.jushu.storbox.actions.ActionShare;
import com.jushu.storbox.actions.NodeAction;
import com.jushu.storbox.actions.ThumbnailAction;
import com.jushu.storbox.adapter.LinkListAdapter;
import com.jushu.storbox.constant.Constant;
import com.jushu.storbox.constant.IntentConstant;
import com.jushu.storbox.constant.MessageCode;
import com.jushu.storbox.constant.UiConstant;
import com.jushu.storbox.entities.FileFolderInfo;
import com.jushu.storbox.entities.FileType;
import com.jushu.storbox.entities.SharedUser;
import com.jushu.storbox.handler.ClientExceptionRelateHandler;
import com.jushu.storbox.util.DirectoryUtil;
import com.jushu.storbox.util.LogUtil;
import com.jushu.storbox.util.PublicTools;
import com.jushu.storbox.view.dialog.ClouddriveDialog;
import com.huawei.sharedrive.sdk.android.modelV3.response.LinkInfoV3;

public class ActionLinkActivity extends BaseTitleActivity {

	private static final String LOG_TAG = ActionLinkActivity.class.getSimpleName();

	public final static int SUCCESS_GET_SHARED_FRIENDS = 0x100001;

	private FileFolderInfo mInfo;
	private String iconPath;
	private List<LinkInfoV3> list;
	private ListView linkListView;
	private ImageView itemIcon;
	private TextView itemName;
	private TextView itemDate;
	private TextView splitText;

	private LinkListAdapter adapter = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_action_newlink);
		setCurrentTitle(this.getString(R.string.link));
		// init data
		Intent intent = getIntent();
		mInfo = (FileFolderInfo) intent.getSerializableExtra(IntentConstant.INTENT_LINK_DATA);

		// init title
		switchTypeOne();
		setCurrentRightIcon(R.mipmap.ic_menu_sharelink_add);

		// init content view
		itemIcon = (ImageView) findViewById(R.id.item_type_img);
		itemName = (TextView) findViewById(R.id.item_name_text);
		itemDate = (TextView) findViewById(R.id.item_date_text);
		linkListView = (ListView) findViewById(R.id.share_link_lv);
		splitText = (TextView) findViewById(R.id.splitText);
		splitText.setText(formatRecepit());
		if (mInfo != null) {
			itemName.setText(mInfo.getName());
			itemDate.setText(formatDate());
			itemIcon.setImageResource(getTypeImgeID());
		}

		

		// LinkInfoV2 linkInfo = new LinkInfoV2();
		// linkInfo.setAccess("Download&Upload");
		// linkInfo.setCreatedAt(new Date().getTime());
		// linkInfo.setExpireAt(new Date().getTime());
		// linkInfo.setEffectiveAt(new Date().getTime());
		// linkInfo.setUrl("https://onebox.com");
		// linkInfo.setPlainAccessCode("d3e&df");
		// linkList.add(linkInfo);
		new NodeAction().getLinkList(this, mInfo, msgHandler);
	}

	private Context getContext() {
		return ActionLinkActivity.this;
	}

	@Override
	protected void onLeftClicked(View clickView) {
		super.onLeftClicked(clickView);
		finish();
	}

	@Override
	protected void onRightClicked(View clickView) {
		if (adapter == null) {
			return;
		} else {
			if (adapter.getLinkList().size() < 3) {
				new NodeAction().createLink(this, mInfo, msgHandler);
			} else {
				Toast.makeText(this, R.string.less_than_three, Toast.LENGTH_SHORT).show();
			}
		}
	}

	private void loadImagIcon() {
		try {
			iconPath = DirectoryUtil.genThumbnailFileFullName(getBaseContext(), mInfo.getOwnerBy(), mInfo.getId(), mInfo.getName());
			File thumBnail2 = new File(iconPath);
			if (!thumBnail2.exists()) {
				new ThumbnailAction().downloadThumbnailIcon(getBaseContext(), mInfo.getOwnerBy(), mInfo.getId(), iconPath, msgHandler);
			} else {
				Message msg_download = new Message();
				msg_download.what = MessageCode.REQUEST_THUMBNAIL_INLOCAL;
				msgHandler.sendMessage(msg_download);
			}
		} catch (Exception e) {
			e.printStackTrace();
			LogUtil.e(TAG, "[getTypeImgeID] fileType is image that show fail..." + e.getLocalizedMessage());
		}
	}

	private String formatDate() {
		SimpleDateFormat timeDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm");
		return timeDateFormat.format(mInfo.getModifiedAt());
	}

	private int getTypeImgeID() {
		// LogUtil.i(TAG, "getTypeImgeID...");
		int typeImgResId = R.mipmap.default_file_icon;
		if (mInfo.getIsFile() == FileType.File.value()) {
			if (PublicTools.isFileType(mInfo.getName(), Constant.WORD_TYPE)) {
				typeImgResId = R.mipmap.doc;
			} else if (PublicTools.isFileType(mInfo.getName(), Constant.PPT_TYPE)) {
				typeImgResId = R.mipmap.ppt;
			} else if (PublicTools.isFileType(mInfo.getName(), Constant.IMAGE_TYPE)) {
				typeImgResId = R.mipmap.empty_pic;
				loadImagIcon();
			} else if (PublicTools.isFileType(mInfo.getName(), Constant.RAR_TYPE)) {
				typeImgResId = R.mipmap.rar;
			} else if (PublicTools.isFileType(mInfo.getName(), Constant.ZIP_TYPE)) {
				typeImgResId = R.mipmap.rar;
			} else if (PublicTools.isFileType(mInfo.getName(), Constant.VIDEO_TYPE)) {
				typeImgResId = R.mipmap.video;
			} else if (PublicTools.isFileType(mInfo.getName(), Constant.MUSIC_TYPE)) {
				typeImgResId = R.mipmap.music;
			} else if (PublicTools.isFileType(mInfo.getName(), Constant.TXT_TYPE)) {
				typeImgResId = R.mipmap.txt;
			} else if (PublicTools.isFileType(mInfo.getName(), Constant.PDF_TYPE)) {
				typeImgResId = R.mipmap.pdf;
			} else if (PublicTools.isFileType(mInfo.getName(), Constant.EXCEL_TYPE)) {
				typeImgResId = R.mipmap.excel;
			} else {
				typeImgResId = R.mipmap.default_file_icon;
			}
		} else {
			typeImgResId = R.mipmap.folder_im;
		}
		return typeImgResId;
	}

	ClientExceptionRelateHandler msgHandler = new ClientExceptionRelateHandler() {
		@SuppressWarnings("unchecked")
		public void handleMessage(final Message msg) {
			switch (msg.what) {
			case MessageCode.REQUEST_THUMBNAIL_INLOCAL:
				new Thread(new Runnable() {
					public void run() {
						LogUtil.i(TAG, "thumb path: " + iconPath);
						Bitmap bmp = BitmapFactory.decodeFile(iconPath);
						ShareDriveApplication.getInstance().addCloudBitmaps(bmp);
						Message message = new Message();
						message.what = UiConstant.UPDATE_TYPE_ICON;
						message.obj = bmp;
						msgHandler.sendMessage(message);
					}
				}).start();
				break;
			case MessageCode.LINK_DELETE:
				LinkInfoV3 linkInfo = (LinkInfoV3) msg.obj;
				List<LinkInfoV3> llist = adapter.getLinkList();
				llist.remove(linkInfo);
				splitText.setText(formatRecepit());
				adapter.notifyDataSetChanged();
				break;
			case MessageCode.LINK_LIST:
				 list = (List<LinkInfoV3>) msg.obj;
				 splitText.setText(formatRecepit());
				adapter = new LinkListAdapter(ActionLinkActivity.this, 0, mInfo, list) {
					@Override
					public void deleteLink(final FileFolderInfo node, final LinkInfoV3 linkInfo) {

						final ClouddriveDialog delete = new ClouddriveDialog(ActionLinkActivity.this, R.style.dialog_upload, R.layout.dialog_linkdelete);
						View conventView = delete.getConventView();
						Button dialog_cancal = (Button) conventView.findViewById(R.id.dialog_del_link_cancel_bt);
						Button dialog_OK = (Button) conventView.findViewById(R.id.dialog_del_link_ok_bt);
						WindowManager windowManager =getWindowManager();
						Display display=windowManager.getDefaultDisplay();
						delete.setWidth(display.getWidth());
						delete.setPosition(Gravity.CENTER_HORIZONTAL,Gravity.CENTER_VERTICAL);
						dialog_cancal.setOnClickListener(new View.OnClickListener() {
							@Override
							public void onClick(View v) {
								delete.dismiss();
							}
						});

						dialog_OK.setOnClickListener(new View.OnClickListener() {
							@Override
							public void onClick(View v) {
								delete.dismiss();
								new NodeAction().deleteLink(ActionLinkActivity.this, node, linkInfo, msgHandler);
							}
						});
						delete.show();
					}

					@Override
					public void editLink(FileFolderInfo node, LinkInfoV3 linkInfo) {
						new NodeAction().getLinkConfig(ActionLinkActivity.this, node, linkInfo, msgHandler);
					}
				};
				linkListView.setAdapter(adapter);
				break;
			case MessageCode.LINK_CONFIG:
				Bundle editBundle = msg.getData();
				Intent editLinkIntent = new Intent();
				editLinkIntent.setAction(IntentConstant.LINK_UPDATE_FINISH + "");
				editLinkIntent.setClass(ActionLinkActivity.this, EditLinkActivity.class);
				editLinkIntent.putExtras(editBundle);
				startActivityForResult(editLinkIntent, IntentConstant.LINK_UPDATE_FINISH);
				break;
			case MessageCode.LINK_CREATE:
				Bundle lBundle = msg.getData();
				Intent addLinkIntent = new Intent();
				addLinkIntent.setClass(ActionLinkActivity.this, EditLinkActivity.class);
				addLinkIntent.putExtras(lBundle);
				addLinkIntent.setAction(IntentConstant.LINK_CREATE_FINISH + "");

				startActivityForResult(addLinkIntent, IntentConstant.LINK_CREATE_FINISH);
				break;
			case UiConstant.UPDATE_TYPE_ICON:// refresh image ui
				Bitmap bmp = (Bitmap) msg.obj;
				if (null != bmp) {
					itemIcon.setImageBitmap(bmp);
				} else {
					LogUtil.e(TAG, "bitmap is null, show default img...");
				}
				break;

			case UiConstant.SHARE_ACTION_DELETE_SHARE_SHIPS_SUCCESS:
				// SharedUser user = (SharedUser) msg.obj;
				// shareADuserList.remove(user);
				// if (shareFileUserAdapter != null) {
				// shareFileUserAdapter.notifyDataSetChanged();
				// }
				// friendsRecepit.setText(formatRecepit());

				splitText.setText(formatRecepit());

				break;

			default:
				super.handleMessage(msg);
			}
		}

		@Override
		public Context getContext() {
			return getBaseContext();
		}
	};


	private String formatRecepit() {

		String str = getResources().getString(R.string.link_with_number);
		String strReturn = getResources().getString(R.string.link);

		if( list !=null){
			if (list.size() > 0) {
				strReturn = String.format(str, list.size());
			}
		}
		return strReturn;
	}

	public void onViewClick(View view, SharedUser data) {
		switch (view.getId()) {
		case R.id.shared_friends_delete:
			new ActionShare().deleteShareShips(getBaseContext(), data, ShareDriveApplication.getInstance().getWnerID(), msgHandler);
			break;

		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case IntentConstant.LINK_CREATE_FINISH:
			switch (resultCode) {
			case IntentConstant.LINK_CREATE_FINISH:
				Bundle lBundle = data.getExtras();
				LinkInfoV3 link = (LinkInfoV3) lBundle.getSerializable("LinkInfo");
				adapter.getLinkList().add(link);
				splitText.setText(formatRecepit());
				adapter.notifyDataSetChanged();
				break;
			default:
				break;
			}
			break;
		case IntentConstant.LINK_UPDATE_FINISH:
			new NodeAction().getLinkList(this, mInfo, msgHandler);
			break;
		default:
			break;
		}
	}

}
